package com.bsj.travel.process.consumer.rocketmq;

import com.alibaba.fastjson2.JSON;
import com.bsj.travel.config.rocketmq.constant.ConsumerGroupConstant;
import com.bsj.travel.constant.BaseServerTopicConstants;
import com.bsj.travel.constant.MqttTopicPowerConstants;
import com.bsj.travel.def.monitor.CloudLog;
import com.bsj.travel.process.handle.service.DefaultTdEngineService;
import com.bsj.travel.util.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author yinhao
 * @version 1.0
 * @description 日志消息存储处理
 * @date 2024/2/22
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = BaseServerTopicConstants.TRAVEL_MQTT_LOG_MSG_RECORD_TOPIC,
        consumerGroup = ConsumerGroupConstant.TRAVEL_MQTT_LOG_MSG_GROUP,
        selectorExpression = BaseServerTopicConstants.TRAVEL_MQTT_LOG_MSG_RECORD_TAG,
        messageModel = MessageModel.CLUSTERING)
public class MqttActionMsgRecordRocketmqConsumer implements RocketMQListener<MessageExt>, RocketMQPushConsumerLifecycleListener {

    @Autowired
    private DefaultTdEngineService defaultTdEngineService;

    @Override
    @Async("travelAsync-mqttMsg-process")
    public void onMessage(MessageExt ext) {
        String message = new String(ext.getBody());
        String tags = ext.getTags();
        log.info("TravelCloud-Mqtt物联网平台数据处理器日志存储tag: {}, msg: {}", tags, message);
        try {
            CloudLog cloudLog = JSON.parseObject(message, CloudLog.class);
            //日志文件存储
//            LogSaveQueue.push(JSON.toJSONBytes(cloudLog));
            //TODO 时序数据存储
            defaultTdEngineService.doPush(JSON.toJSONBytes(cloudLog));
        } catch (Exception e) {
            log.error("TravelCloud-Mqtt物联网平台数据处理器日志存储-->消费失败，失败原因： {}", ExceptionUtil.getStackStr(e));
        }
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
        // 设置消费者消息重试次数
        defaultMQPushConsumer.setMaxReconsumeTimes(3);
        //设置实例名称
        defaultMQPushConsumer.setInstanceName(MqttTopicPowerConstants.MSG_LOG_RECORD_INSTANCE_NAME);
    }
}
